<?php

namespace app\api\service\answers;

use app\api\model\answers\GptToken;
use app\api\service\token\LoginToken;
use app\lib\exception\answers\AnswersException;
use think\Db;
use think\Exception;

class SiderGptService
{
    private static $instance;

    public static function getInstance(): SiderGptService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function gpt($params){
        $result = [];
        $id = 0;
        // 启动事务
        Db::startTrans();
        try {
            $gpt = GptToken::where("type",1)->lock(true)->findOrEmpty();
            if ($gpt->isEmpty()){
                throw new Exception( '当前无账号解析，请20秒后再继续尝试！');
            }
            $id = $gpt->id;
            $gpt->save(['type'=>2,'get_time'=>date("Y-m-d H:i:s")]);
            Db::commit();
            $Authorization = $gpt->token??"";
            $header = array(
                'Content-Type: application/json',
                'Authorization: '.$Authorization
            );
            $result = $this->get_post_json(
                "https://sider.ai/api/v1/completion/text",
                $params,$header);
            GptToken::where("id",$id)->update(['type'=>1]);
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new AnswersException([
                'msg' => $e->getMessage(),
                'error_code' => 20001
            ]);
        }

        return $result;

    }

    public function merge($image_template,$image_target){
        $API_KEY = "6ZlOUjo9oC3GaAmoHCT7PWrg";
        $SECRET_KEY = "24BkoaXdNuwvxEaFTB3Wg8bzjh7zlMaD";
        $url = "https://aip.baidubce.com/oauth/2.0/token?client_id=".$API_KEY."&client_secret=".$SECRET_KEY."&grant_type=client_credentials";
        $headerss = array(
            'Content-Type: application/json',
            'Accept: application/json'
        );
        $data = [
            "version"=>"3.0",
            "image_template"=>[
                "image"=>$image_template,
                "image_type"=>"URL"
//                "image_type"=>"BASE64"
            ],
            "image_target"=>[
                "image"=>$image_target,
                "image_type"=>"URL"
            ]
        ];
        $access_token = curlPost($url,"",$headerss)['access_token'];
        $response = curlPost('https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token='.$access_token,json_encode($data),$headerss);
        return $response;
    }


    public function writingpng($text_arr,$color){
        $uid = LoginToken::getInstance()->getCurrentUid()??"";
        $data = [
            "text_arr"=>json_encode($text_arr),
            "color"=>$color,
            "uid"=>$uid
        ];
        $response = curlPost("http://127.0.0.1:5000//baijiahao/baidu/writingpng",$data);
        return $response;
    }


    private function get_post_json($url = '', $post_data = array(),$header_data = array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($ch,CURLOPT_HTTPHEADER, $header_data);// 文本提交方式，必须声明请求头
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        // 设置请求超时时间，单位是秒
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        $data = curl_exec($ch);//运行curl
        if($data === false){
            var_dump(curl_error($ch));
        }else{
            curl_close($ch);
            return json_decode($data);
        }
    }



}
